package com.cnooc.aicv.lmapp.service;

import com.cnooc.aicv.lmapp.model.LMDiagMsg;
import com.cnooc.aicv.lmapp.model.LmResult;
import com.cnooc.aicv.lmapp.util.HttpsUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@Service
public class SafetyHatChecker {

    private static final String API_URL = "https://10.78.170.53/v1/chat/completions"; // 替换为实际的API地址
    private static final String LM_TOKEN = "Bearer dhuiawbfuibqweibfiqwbicxsz156'";
    //提示词-安全帽
    private static final String PROMPT_HELMET = "请判断图中人员如果没戴安全帽回答yes，如果戴了安全帽回答no。只需要回答yes或者no即可，不需要解释。，回答格式要求：用json格返回，json格式要求：jsonsafety_risk:yes or no";
    private LmPromptMaker promptMaker = new LmPromptMaker();

    public String checkIfWearingSafetyHat(String base64Image, String prompt) throws Exception {
        // 创建HTTP客户端
        HttpClient client = HttpClient.newHttpClient();

        // 构建请求体
        String requestBody = createRequestBody(base64Image, prompt);

        // 构建POST请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
                .build();

        // 发送请求并获取响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 处理响应
        if (response.statusCode() == 200) {
            String responseBody = response.body();
            return parseResponse(responseBody);
        } else {
            throw new RuntimeException("Failed to call the API: " + response.statusCode());
        }
    }

    private String createRequestBody(String base64Image, String prompt) {
        return String.format("{\"model\": \"qwen2.5-vl\"," +
                             "\"messages\": [{" +
                             "\"role\": \"user\"," +
                             "\"content\": [{" +
                             "\"type\": \"image_url\"," +
                             "\"image_url\": {\"url\": \""+base64Image+"\"}" +
                             "},{" +
                             "\"type\": \"text\"," +
                             "\"text\": \""+prompt+"\"" +
                             "}]" +
                             "}]," +
                             "\"temperature\": 0.1," +
                             "\"top_p\": 0.8," +
                             "\"repetition_penalty\": 1.05," +
                             "\"max_tokens\": 8192" +
                             "}" );
    }

    private String parseResponse(String responseBody) {
        // 假设响应体是一个JSON字符串
        // 解析响应体中的内容
        // 这里假设响应体包含一个字段 "result"，其值为 "yes" 或 "no"
        // 你需要根据实际情况解析响应体
        if (responseBody.contains("\"result\":\"yes\"")) {
            return "yes";
        } else if (responseBody.contains("\"result\":\"no\"")) {
            return "no";
        } else {
            throw new RuntimeException("Unexpected response format: " + responseBody);
        }
    }

    private OkHttpClient client = HttpsUtil.getUnsafeOkHttpClient().build();
    public LmResult sendSSLRequestPre(String allarType, String base64Image){
        LmResult result = new LmResult();
        //if(parampass)
        //if(isHelMet)
        String prompt = getPromptByType(allarType);
        sendSSLRequest(API_URL, LM_TOKEN, base64Image, prompt, result);
        return result;
    }

    private String getPromptByType(String allarType) {
//        if(=="安全帽")
//        return PROMPT_HELMET;
        return promptMaker.makePrompt(allarType);
    }

    public void sendSSLRequestDef(){
        sendSSLRequest(API_URL, LM_TOKEN, null,null, null);
    }
    private void sendSSLRequest(String url, String token , String base64Image, String prompt, LmResult result) {
        // 构建请求头，携带 token
        Headers headers = new Headers.Builder()
                .add("Authorization", token)
               // .add("Content-Type", "application/json")
                .build();

        //根据模板创建
        String body = loadTemplateHelet(base64Image, prompt);

        // 构建 GET 请求
        //RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), "{}");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body);
        log.debug("requestBody: {}", body);
        Request request = new Request.Builder()
                .url(url)
                //.get()  // GET 请求
                .post(requestBody)
                .headers(headers)
                .build();
        log.debug("request: {}", request);
        // 执行请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            // 判断响应是否成功 (状态码 2xx)
            if (response.body() != null) {
                result.setMessage(response.body().string());
            }
            log.debug(">>>>>>>>>>>>>>response{}", result.getMessage());
            if (response.isSuccessful()) {
                // 处理响应数据
               // String responseString = response.body().string();
               // log.info("---------Response for url {}: {}", url, responseString);

                // 解析响应 JSON（使用 optInt() 获取字段）

           } else {
                // 如果响应失败，输出错误信息
                log.error("Request failed for url {} with status code: {}", url, response.code());
            }
        } catch (IOException e) {
            log.error("Request failed for url {} due to network error: {}", url, e.getMessage(), e);
        } catch (Exception e) {
            log.error("Unexpected error for url {}: {}", url, e.getMessage(), e);
        }
    }

    private String loadTemplateHelet(String base64Image, String prompt) {
        LmDiagFilterImp lmDiagMsgImp =  new LmDiagFilterImp();

        String jsonFile = promptMaker.getJsonFile();

        String jsonStr = null;
        try {
            jsonStr = Files.readString(Paths.get(jsonFile));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        LMDiagMsg lmDiagMsg = null;
        try {
            lmDiagMsg = objectMapper.readValue(jsonStr, LMDiagMsg.class);
            lmDiagMsg.setBase64New(base64Image);
            lmDiagMsg.setPromptNew(prompt);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        String jsonStr0;
        try {
             jsonStr0 = lmDiagMsgImp.doFilterJonn(objectMapper, lmDiagMsg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonStr0;
    }

    public static void main(String[] args) {
        try {
            SafetyHatChecker checker = new SafetyHatChecker();
//            String base64Image =
            String base64Image = Files.readString(Paths.get("C:\\Users\\liych46\\Downloads\\aicv-master\\aicv-lm-app\\src\\main\\resources\\base64"));
            log.info(""+base64Image.length());
            //= FileLoader.readBase64FileFromResources("base64.txt"); // 替换为你的Base64编码图片
            //String result = checker.checkIfWearingSafetyHat(base64Image);
           String base64Image2 = "";
//                    ImageToBase64.encodeImageToBase64("C:\\Users\\liych46\\Downloads\\aicv-master\\aicv-lm-app\\src\\main\\resources\\4.png");
            log.info(""+base64Image2.length());
            log.info("{}",base64Image2.equals(base64Image));
            String result = "";
            checker.sendSSLRequest(API_URL, LM_TOKEN, base64Image, PROMPT_HELMET, null);
            System.out.println(result); // 输出 "yes" 或 "no"
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public LmPromptMaker getPromptMaker() {
        return promptMaker;
    }
}